#include "httpclient.h"
#include <QTimer>
#include <QByteArray>


#define HTTP_RESPONSE_OK 0
#define HTTP_RESPONSE_AUTH_ERR 1
#define HTTP_RESPONSE_TIMEOUT 2
#define HTTP_RESPONSE_CONN_REFUSED 3
#define HTTP_RESPONSE_UKNOW_ERR 4



HttpClient::HttpClient()
{

}

HttpClient::~HttpClient()
{

}

HttpClient* HttpClient::m_instance = NULL;
HttpClient* HttpClient::getInstance()
{
    if (m_instance == NULL)
    {
        m_instance = new HttpClient;
    }
    return m_instance;
}

QString HttpClient::post(QString fullRequest, int msec)
{
    QString res;
    QTimer timer;
    timer.setInterval(msec);  // 设置超时时间 30 秒
    timer.setSingleShot(true);  // 单次触发

    QNetworkAccessManager Manager;
    // 创建一个QJsonObject来发送数据
    QJsonObject jsonObject;
    jsonObject["key1"] = "value1";
    jsonObject["key2"] = "value2";
    QJsonDocument jsonDoc(jsonObject);
    QByteArray jsonBytes = jsonDoc.toJson();


    QNetworkRequest request(fullRequest);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QNetworkReply *pReply = Manager.post(request, jsonBytes);


    QEventLoop loop;
    QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    QObject::connect(pReply, SIGNAL(finished()), &loop, SLOT(quit()));
    timer.start();
    loop.exec(QEventLoop::ExcludeUserInputEvents);  // 启动事件循环

    if (timer.isActive()) {  // 处理响应
        timer.stop();
        if (pReply->error()) {
            qDebug() << "Error:" << pReply->errorString();
        } else {
            QByteArray responseBytes = pReply->readAll();
            res = QString::fromUtf8(responseBytes);
        }
        pReply->deleteLater();

    } else {  // 处理超时
        QObject::disconnect(pReply, SIGNAL(finished()), &loop, SLOT(quit()));
        pReply->abort();
        pReply->deleteLater();

        qDebug() << "timeout.....";

    }
    return res;
}




